package com.soul.dj.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.soul.dj.MainApplication;
import com.soul.dj.R;
import com.soul.dj.util.Const;
import com.soul.dj.util.http.JSONCallBack;
import com.soul.dj.util.http.MediaType;
import com.soul.dj.util.http.json.JsonProcessUtil;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @ClassNmae PhotoListActivity
 * @create 2018-09-17 15:02
 **/
public class PhotoListActivity extends BaseActivity {

    private List<Map<String, String>> grades = new ArrayList<Map<String, String>>();

    private final static int REQUEST_CODE = 101;

    private List list = new ArrayList();

    private GridView gridView;

    private List<Map<String,Object>> items = new ArrayList<Map<String,Object>>();
    private ArrayAdapter<Map<String,Object>> adapter;

    private int page = 1;
    private boolean pull_up_lock;// 锁定上拉
    private View footerView;

    private int lastVisibleItemPosition = 0;// 标记上次滑动位置，初始化默认为0
    private boolean scrollFlag = false;// 标记是否滑动

    private String recid = "";

    private ArrayList<String> pathList = new ArrayList<>();

    private List<LocalMedia> mediaList = new ArrayList<>();

    private Map<String,Object> map = null;



    @Override
    protected void initView() {
        recid = getIntent().getStringExtra("recId");

        setContentView(R.layout.photo_list_activity);
        findViewById(R.id.finish).setOnClickListener(this);
        findViewById(R.id.saveBtn).setOnClickListener(this);
        ((TextView)findViewById(R.id.title)).setText("现场照片与小视频");


        gridView = findViewById(R.id.gridView);

        adapter = new ArrayAdapter<Map<String,Object>>(this, android.R.layout.simple_list_item_1, items){

            @Override
            public View getView(final int position, View convertView, final ViewGroup parent) {

                View	view = convertView;
                final ViewHolder holder;

                final Map<String,Object> item = items.get(position);
                if(view == null){
                    view = getLayoutInflater().inflate(R.layout.photo_list_item, null);
                    holder = new ViewHolder();
                    holder.imageView = view.findViewById(R.id.imageView);
                    holder.delete = view.findViewById(R.id.delete);

                    view.setTag(holder);
                }else{
                    holder = (ViewHolder) view.getTag();
                    holder.delete.setVisibility(View.GONE);
                }

                Picasso.get().load(R.drawable.add).into(holder.imageView);
                view.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (position == 0){
                            startPhoto();
                        }
//                        else{
//                            if (item.get("path") != null && !TextUtils.isEmpty(item.get("path").toString())){
//
//                                 String path = item.get("path").toString();
//                                 if (TextUtils.equals("video", Util.getMIMEType(new File(path)))){
//                                     PictureSelector.create(PhotoListActivity.this).externalPictureVideo(path);
//                                 }else if (TextUtils.equals("audio", Util.getMIMEType(new File(path)))){
//                                     PictureSelector.create(PhotoListActivity.this).externalPictureVideo(path);
//                                 }else if (TextUtils.equals("image", Util.getMIMEType(new File(path)))){
//                                     PictureSelector.create(PhotoListActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, mediaList);
//
//                                 }
//                            }
//
//                        }
                    }
                });

                if (position != 0){

                    holder.delete.setVisibility(View.VISIBLE);
                    if (item.get("path") == null || TextUtils.isEmpty(item.get("path").toString())){
                        Picasso.get().load(item.get("photourl").toString()).placeholder(R.drawable.image_placeholder).error(R.drawable.video).into(holder.imageView);
                    }else{

                        Picasso.get().load("file://"+item.get("path").toString()).placeholder(R.drawable.image_placeholder).error(R.drawable.video).into(holder.imageView);
                    }
                }


                holder.delete.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {

                        map = item;

                        if (item.get("photoid") == null){

                            items.remove(item);
                            pathList.remove(item.get("path").toString());
                            adapter.notifyDataSetChanged();

                        }else{

                            Map<String,Object> paramsMap = new HashMap<>();
                            paramsMap.put("photoid", String.valueOf(item.get("photoid")));
//                            sendHttp(Const.REQUEST_URL_DELETEFILE,MediaType.JSON,paramsMap,new JSONCallBack<Map>(PhotoListActivity.this,"delete", Map.class));
                        }


                    }
                });



                return view;
            }
        };

        gridView.setAdapter(adapter);

        Map<String,Object> map = new HashMap<>();
        map.put("path",R.drawable.add);
        items.add(map);
        adapter.notifyDataSetChanged();
        initLoadData();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                   mediaList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    initList();

                    for (LocalMedia baseMedia: mediaList ) {
                        String spath = baseMedia.getPath();
                        if (baseMedia.isCut()){
                            spath = baseMedia.getCutPath();
                        }
                        if (baseMedia.isCompressed()){
                            spath = baseMedia.getCompressPath();
                        }
                        Log.d("yhbsoul",spath);
                        pathList.add(spath);
                        Map<String,Object> map = new HashMap<>();
                        map.put("path",spath);
                        items.add(map);
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.finish:
                MainApplication.removeActivity(this);
                break;
            case R.id.saveBtn:

                if (pathList.size() == 0){
                    toast("请选择照片或小视频");
                    return;
                }

                Map<String,Object> params = new HashMap<>();
                params.put("recid",recid);

//                sendHttpFiles(Const.REQUEST_URL_SAVEFILES, params,"multipartFile",pathList,new JSONCallBack<Map>(this,"save", Map.class));

                break;
        }
    }

    private void initLoadData() {

        page = 1;
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("recid", recid);
//        sendHttp(Const.REQUEST_URL_GETFILES,MediaType.JSON,paramsMap,new JSONCallBack<Map>(this,"lodeData", Map.class));


    }

    private void initList(){
        items.clear();
        pathList.clear();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("path",R.drawable.add);
        items.add(map1);
        if (list != null && list.size() > 0) {

            for (Object object : list) {
                try {
                    String tmp = JsonProcessUtil.beanToJson(object);
                    Map<String,Object> good = JsonProcessUtil.jsonToBean2(tmp , Map.class);
                    items.add(good);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    public void onAjaxOK(Object result, String tag) {
        super.onAjaxOK(result, tag);
        if(TextUtils.equals("lodeData", tag)){

            Map map = (Map) result;
            list = (List) map.get("searchList");

            initList();
            page++;
            adapter.notifyDataSetChanged();
        }else if(TextUtils.equals("save",tag)){
            toast("保存成功");
            PictureFileUtils.deleteCacheDirFile(this);
            pathList.clear();
            mediaList.clear();
            initLoadData();
        }else if (TextUtils.equals(tag,"delete")){
//            items.remove(map);
            initLoadData();
        }
    }



    private class ViewHolder{

        private ImageView imageView,delete;
    }

    private void startPhoto(){
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(PhotoListActivity.this)
                .openGallery(PictureMimeType.ofAll())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(9-list.size())// 最大图片选择数量 int
//                .minSelectNum()// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(true)// 是否可预览视频 true or false
                .enablePreviewAudio(true) // 是否可播放音频 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath(Const.IMAGE_PATH)// 自定义拍照保存路径,可不填
                .enableCrop(true)// 是否裁剪 true or false
                .compress(false)// 是否压缩 true or false
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(3,4)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(true)// 是否显示gif图片 true or false
                .compressSavePath(Const.IMAGE_PATH)//压缩图片保存地址
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(false)// 是否开启点击声音 true or false
                .selectionMedia(mediaList)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                .cropCompressQuality()// 裁剪压缩质量 默认90 int
//                .minimumCompressSize(100)// 小于100kb的图片不压缩
//                .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .videoQuality(1)// 视频录制质量 0 or 1 int
                .videoMaxSecond(60)// 显示多少秒以内的视频or音频也可适用 int
                .videoMinSecond(5)// 显示多少秒以内的视频or音频也可适用 int
                .recordVideoSecond(60)//视频秒数录制 默认60s int
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }
}
